#include "common.h"

/*** Echo-server ***/

int main() {
    int listener;
    struct sockaddr_in addr;
    struct sockaddr_in client;
    socklen_t size_of_client;
    char buf[BUF_SIZE];

    listener = socket(AF_INET, SOCK_DGRAM, 0);
    if (listener < 0) {
        perror("Error in socket creation");
        return errno;
    }

    addr.sin_family = AF_INET;
    addr.sin_port = htons(MY_PORT);
    addr.sin_addr.s_addr = htonl(INADDR_ANY);

    if (bind(listener, (struct sockaddr*) &addr, sizeof(addr)) < 0) {
        perror("Error in binding");
        return errno;
    }

    listen(listener, 1);
    while (1) {
        int bytes_read = recvfrom(listener, buf, BUF_SIZE, 0, (struct sockaddr*) &client, &size_of_client);
        if (bytes_read > 0) {
            sendto(listener, buf, bytes_read, 0, (struct sockaddr*) &client, size_of_client);
            buf[bytes_read] = 0;
            printf("Server: I received from client: %s\n", buf);
        }
    }
    close(listener);
    return 0;
}
